//
//  WKForgetPasswordController.m
//  WeKeTang
//
//  Created by ichina on 2017/8/22.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKForgetPasswordController.h"
#import "WKHomeViewController.h"
#import "WKProfireViewController.h"
#import "WKNavgationController.h"
#import "UIDevice+KZExtension.h"
#import "NSString+MKNetworkKitAdditions.h"
#import "WKNetworkTools.h"
#import "WKLoginHandel.h"
#import "WKUniversal.h"
#import "UMMobClick/MobClick.h"
@interface WKForgetPasswordController ()

@property (weak, nonatomic) IBOutlet UITextField *TFPhoneNum;
@property (weak, nonatomic) IBOutlet UITextField *TFVerifyCode;
@property (weak, nonatomic) IBOutlet UIButton *BtnVerify;
@property (weak, nonatomic) IBOutlet UITextField *TFPassword;
@property (weak, nonatomic) IBOutlet UIButton *BtnComlete;
@property (nonatomic, strong) NSTimer * verifyTimer;
@property (nonatomic, assign) NSInteger verifyCounter;
@property (weak, nonatomic) IBOutlet UIButton *btnShowPsd;
@property (nonatomic, copy) NSString *SESSID;
@property (nonatomic, assign) BOOL pwdStatus;
@property (nonatomic, assign) long verifyCode;

@end

@implementation WKForgetPasswordController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _verifyCounter = 60;
     self.pwdStatus = YES;
    self.view.backgroundColor = RGBColor(245, 245, 245);
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    [self setupUI];
}
- (void)setupUI{
    
    self.navItem.title = @"找回密码";
    
    [self setLeftButtonWithImage:@"" highlightedImage:@"" target:self action:@selector(backAction)];
    self.BtnVerify.layer.cornerRadius = 2;
    self.BtnVerify.layer.masksToBounds = YES;
    self.BtnComlete.layer.cornerRadius = 2;
    self.BtnComlete.layer.masksToBounds = YES;
    UIView *leftView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 47)];
    leftView1.contentMode = UIViewContentModeCenter;
    self.TFPhoneNum.leftView = leftView1;
    self.TFPhoneNum.leftViewMode = UITextFieldViewModeAlways;
    self.TFPhoneNum.layer.borderColor = [UIColor colorWithHexString:@"#ededed"].CGColor;
    self.TFPhoneNum.layer.borderWidth = 1;
    
    UIView *leftView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 47)];
    leftView2.contentMode = UIViewContentModeCenter;
    self.TFPassword.leftView = leftView2;
    self.TFPassword.leftViewMode = UITextFieldViewModeAlways;
    self.TFPassword.layer.borderColor = [UIColor colorWithHexString:@"#ededed"].CGColor;
    self.TFPassword.layer.borderWidth = 1;
    
    UIView *leftView3 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 47)];
    leftView3.contentMode = UIViewContentModeCenter;
    self.TFVerifyCode.leftView = leftView3;
    self.TFVerifyCode.leftViewMode = UITextFieldViewModeAlways;
    self.TFVerifyCode.layer.borderColor = [UIColor colorWithHexString:@"#ededed"].CGColor;
    self.TFVerifyCode.layer.borderWidth = 1;
    
//    self.btnShowPsd.layer.borderColor = [UIColor colorWithHexString:@"#ededed"].CGColor;
//    self.btnShowPsd.layer.borderWidth = 1;
    
    self.TFPhoneNum.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.TFVerifyCode.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.TFPassword.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.navgationBar.hidden = NO;
    [self.navgationBar setBarTintColor:[UIColor whiteColor]];
    self.statusbar.backgroundColor = [UIColor whiteColor];
}
- (void)backAction{
    [MobClick profileSignInWithPUID:@"findpwd_back"];
    [super backAction];
}
#pragma mark - 显示密码
- (IBAction)showPasswordAction:(UIButton *)sender {
    
    self.pwdStatus = !self.pwdStatus;
    self.TFPassword.secureTextEntry = self.pwdStatus;
    [self.btnShowPsd setImage:(self.pwdStatus?IMG(@"icon_invisible.png"):IMG(@"icon_pesswordvisible.png")) forState:UIControlStateNormal];

}

#pragma mark - 获取验证码
- (IBAction)getVerificationCodeAction:(UIButton *)sender {
    [MobClick profileSignInWithPUID:@"findpwd_getcode"];
    if (self.verifyCounter<60) {
        [self showCustomAlertMessage:@"一分钟内不能重复获取验证码"];
        return;
    }
   long verifyCode = [self getRandomNumber:1000 to:9999];
    NSString *callBackStr = [WKUniversal validateMobile:self.TFPhoneNum.text];
    if (callBackStr) {
        [self showCustomAlertMessage:callBackStr];
        return;
    }
     [self startTimer];
    
    
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"smsnew" forKey:@"commandid"];
    [para setObject:self.TFPhoneNum.text forKey:@"mobile"];
    [para setObject:_S(@"%.0ld",verifyCode) forKey:@"content"];
    [para setObject:@"2" forKey:@"type"];
    [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        [weakSelf showCustomAlertMessage:@"网络错误"];
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *dic  = dict[@"head"];
        NSString *statuscode = dic[@"statuscode"];
//        [weakSelf showCustomAlertMessage:@"验证码已发送"];
        NSLog(@"获取验证码%@",statuscode);
        if ([statuscode  isEqualToString:@"100"]) {
            weakSelf.verifyCode = verifyCode;
        }
    }];
    NSLog(@"%ld",self.verifyCode);
}
#pragma mark - 完成
- (IBAction)completeAction:(UIButton *)sender {
    [MobClick profileSignInWithPUID:@"findpwd_complete"];
     long verifyCode = [self getRandomNumber:1000 to:9999];
    
    NSString * callBackStr = [WKUniversal validateMobile:self.TFPhoneNum.text];
    if (callBackStr) {
        [self showCustomAlertMessage:callBackStr];
        return;
    }
    if (isExistString(self.TFVerifyCode.text)) {
        [self showCustomAlertMessage:@"验证码不能为空"];
        return;
    }
    
    if ([self.TFPassword.text length]<6 || [self.TFPassword.text length]>18) {
        [self showCustomAlertMessage:@"密码长度不合法"];
        return;
    }
    if (![_S(@"%.0ld",self.verifyCode) isEqualToString:self.TFVerifyCode.text] ) {
        [self showCustomAlertMessage:@"您输入的验证码有误，请从新输入!"];
        return;
    }
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"forgetpwd" forKey:@"commandid"];
    [para setObject:self.TFPhoneNum.text forKey:@"mobile"];
    [para setObject:_S(@"%.0ld",verifyCode) forKey:@"content"];
    [para setObject:self.TFPassword.text forKey:@"newpassword"];
    
    [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"申请中..." completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        [weakSelf showCustomAlertMessage:@"网络错误"];
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *dic  = dict[@"head"];
        NSString *statuscode = dic[@"statuscode"];
        [weakSelf showCustomAlertMessage:@"新密码修改成功"];
        NSLog(@"获取验证码%@",statuscode);
        if ([statuscode  isEqualToString:@"100"]) {
            //新密码注册成功->登录
            //调登录接口
            [weakSelf loadLogin];
            
        }
    }];

}
#pragma mark - 找回成功后调登录接口
- (void)loadLogin{
    
    [MobClick profileSignInWithPUID:@"playerID"];//启动友盟账号统计
    __weak typeof(self) weakSelf = self;
    NSDate *date = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyyMMddhhmmss"];
    NSString *timestamp = [dateformatter stringFromDate:date];
    
    NSString *deviceID = mydeviceUniqueIdentifier();
    NSString *version =[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    NSString *mac= [WKUniversal macaddress];
    
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:self.TFPhoneNum.text forKey:@"account"];
    [para setObject:self.TFPassword.text forKey:@"password"];
    [para setObject:timestamp   forKey:@"timestamp"];
    [para setObject:@"1" forKey:@"sequenceid"];
    [para setObject:@"login" forKey:@"commandid"];
    [para setObject:version forKey:@"version"];
    [para setObject:mac forKey:@"mac"];
    [para setObject:deviceID forKey:@"deviceid"];
    
    [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"登录中..." completionHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSLog(@"登录：%@",dict);
    } errorHandler:^(NSError *error) {
        
        [weakSelf showCustomAlertMessage:@"网络错误"];
        
    } finishHandler:^(id responseObject) {
        
        NSArray * cookieArr = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];//获取cookie
        for (NSHTTPCookie * cookie in cookieArr) {          //遍历cookie
            if ([cookie.name isEqualToString:@"PHPSESSID"]) {
                self.SESSID = cookie.value;
            }
        }
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *dicBody = dict[@"body"];
        NSMutableDictionary *saveDic = [NSMutableDictionary dictionary];
        [saveDic setObject:dicBody[@"userid"] forKey:@"userid"];
        [saveDic setObject:dicBody[@"avatar"] forKey:@"avatar"];
        [saveDic setObject:dicBody[@"account"] forKey:@"account"];
        [saveDic setObject:dicBody[@"nickname"] forKey:@"nickname"];
        [saveDic setObject:self.SESSID forKey:@"SESSID"];
        [WKLoginHandel saveLoginDataWithDict:saveDic.mutableCopy];
        
        NSDictionary *dicHead = dict[@"head"];
        NSLog(@"登录接口：%@",dicHead[@"statuscode"]);
        if ([dicHead[@"statuscode"] intValue] == 100) {
            [self showCustomAlertMessage:@"登录成功"];
            //登录成功
            
            WKHomeViewController *mainVC = [[WKHomeViewController alloc] init];
            mainVC.userId = dicBody[@"userid"];
            WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:mainVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
        }
        
    }];
}

#pragma mark - 开启定时器
- (void)startTimer{
    self.verifyCounter = 60;
    __weak typeof(self) weakSelf = self;
    if (self.verifyTimer && [self.verifyTimer isValid]) {
        [self.verifyTimer invalidate];
    }
    self.verifyTimer = [NSTimer scheduledTimerWithTimeInterval:1 block:^(NSTimer * _Nonnull timer) {
        weakSelf.verifyCounter--;
        if (weakSelf.verifyCounter<=0) {
            [weakSelf stopTimer];
        }
        else{
            [weakSelf.BtnVerify setTitle:_S(@"%ld秒后重试",weakSelf.verifyCounter) forState:UIControlStateNormal];
        }
    } repeats:YES];
}
- (void)stopTimer{
    if (self.verifyTimer && [self.verifyTimer isValid]) {
        [self.verifyTimer invalidate];
        self.verifyTimer = nil;
    }
    self.verifyCounter = 60;
    [self.BtnVerify setTitle:@"获取验证码" forState:UIControlStateNormal];
}
- (long)getRandomNumber:(long)from to:(long)to{
    return (long)(from + (arc4random() % (to - from + 1)));
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view resignFirstResponder];
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
